package com.mdjnu.service.imp;

import com.mdjnu.mapper.VideoMapper;
import com.mdjnu.pojo.Result;
import com.mdjnu.pojo.Videos;
import com.mdjnu.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@SuppressWarnings("all")
@Service
public class VideoServiceImp implements VideoService
{
    @Value("${save.video.path}")// 视频保存路径
    private String  filePath;
    @Autowired// 注入VideoMapper// 注入VideoMapper
    private VideoMapper  videoMapper;
    @Override//  上传视频
    public Result uploadVideo(MultipartFile video) {
        //  判断文件是否为空
        if (video.isEmpty()) {
            return Result.error("上传文件为空");
        }

        if (video.getSize() > 1024 * 1024 * 50) {
            return Result.error("上传文件大小不能超过50M");
        }

        // 随机生成文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");

        // 获取文件类型
        String fileType = video.getContentType().replaceAll("video/", "");

        try {
            // 保存文件
            File file = new File(filePath+fileName + "." + fileType);
            if (!file.exists()) {
                file.mkdirs();
            }
            video.transferTo(new java.io.File(filePath + fileName + "." + fileType));
            // 返回文件路径
            return Result.success(fileName + "." + fileType);
        } catch (Exception e) {
            // 返回错误信息
            return Result.error("上传文件失败");
        }
    }

    @Override
    public Result addVideo(Videos videos) {
        //  TODO: 添加视频
        // 设置更新时间
        videos.setUploadTime(java.time.LocalDateTime.now());
        // 获得视频本地位置
        String videoPath = filePath+videos.getCoverUrl();
        // 获得视频时长（单位：秒）
        //  TODO: 获取视频时长
        int duration = (int) (videoPath.length() / 1024 * 8 / 1024);
        videos.setDuration(duration);
        // 设置默认值
        videos.setViewCount(0);
        videos.setLikeCount(0);
        videos.setDislikeCount(0);
        videos.setCommentCount(0);
        videos.setStatus(6);
        videoMapper.insert(videos);
        return Result.success();
    }

    @Override
    public Result compressImage(MultipartFile image) {
        if (image.isEmpty()) {
            return Result.error("上传文件为空");
        }
        if (image.getSize() > 1024 * 1024 * 50) {
            return Result.error("上传文件大小不能超过50M");
        }

        // 随机生成文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");

        // 获取文件类型
        String fileType = image.getContentType().replaceAll("image/", "");

        //读取图片，进行压缩
        try {//  读取图片
            String imagePath = filePath+fileName + "." + fileType;

            BufferedImage bufferedImage = ImageIO.read(image.getInputStream());

            if (bufferedImage == null){
                return Result.error("无法读取图片");
            }

            if (bufferedImage.getWidth() > 800 || bufferedImage.getHeight() > 800){
                bufferedImage = compressImage(bufferedImage);
                // 保存图片到指定路径
                File file = new File(imagePath);
                ImageIO.write(bufferedImage, fileType, file);
                return Result.success(fileName+"."+fileType);
            }

        } catch (IOException e) {
            return Result.error("上传图片失败");
        }

        return null;
    }

    @Override
    public Result getVideoByHot(int pageNum, int pageSize) {
        int stater = (pageNum - 1) * pageSize;
        return Result.success(videoMapper.findHotVideo(stater,pageSize,6));
    }

    @Override
    public Result getVideoByNew(int pageNum, int pageSize) {
        int stater = (pageNum - 1) * pageSize;
        return Result.success(videoMapper.findNewVideo(stater,pageSize,6));
    }

    @Override
    public Result getVideoByView(int pageNum, int pageSize) {
        int stater = (pageNum - 1) * pageSize;
        return Result.success(videoMapper.findByViewCount(stater,pageSize,6));
    }

    @Override
    public Result getVideoByComment(int pageNum, int pageSize) {
        int stater = (pageNum - 1) * pageSize;
        return Result.success(videoMapper.findByCommentCount(stater,pageSize,6));
    }

    @Override
    public Result getVideoById(int videoId) {
        if (videoId<=0) {
            return Result.error("参数错误");
        }
        return Result.success(videoMapper.findByVideoId(videoId));
    }

    private BufferedImage compressImage(BufferedImage originalImage) {
        int width = originalImage.getWidth() / 2;
        int height = originalImage.getHeight() / 2;


        BufferedImage compressedImage = new BufferedImage(width, height, originalImage.getType());
        Graphics2D g2d = compressedImage.createGraphics();
        g2d.drawImage(originalImage, 0, 0, width, height, null);
        g2d.dispose();

        return compressedImage; // 返回压缩后的图片
    }

}
